package com.huiminpay.merchant.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.huiminpay.merchant.service.IFileHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


@Service
public class IFileHandlerImpl implements IFileHandler {

    @Value("${aliyun.oss.domain}")
    String domain;

    @Value("${aliyun.oss.bucket}")
    String bucket;

    @Autowired
    OSS oss;

    @Override
    public String fileUpload(MultipartFile multipartFile) {

        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + suffix;

        try {
            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(bucket, newFileName, multipartFile.getInputStream());
            oss.putObject(putObjectRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return domain + newFileName;
    }

    @Override
    public void fileDownload(String fileName) {

        GetObjectRequest getObjectRequest = new GetObjectRequest(bucket,fileName);

        oss.getObject(getObjectRequest,new File("D:/huiminpayImg/"+fileName));


    }

}
